import json
import base64
import re
from .logConf import log
from functools import wraps
import json
from util.logConf import log
from .PyMysql import PyMysql
import hashlib


def BasicAuth(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        request_handler = args[0]

        def auth_fail(reason):
            request_handler.write(json.dumps({"success": False, "error": reason}))
            request_handler.set_status(401)
            return request_handler.finish()

        ip_remote = request_handler.request.remote_ip
        headers = request_handler.request.headers
        if 'Authorization' not in headers:
            return auth_fail('need basic auth header:Authorization')
        auth_header = headers['Authorization']
        if not re.match(r'[bB][aA][sS][iI][cC] .', auth_header):
            return auth_fail('invalid Authorization header format')
        basic_str = auth_header.split()[1]
        decode_str = base64.b64decode(basic_str).decode()
        username, password = decode_str.split(':')
        log.debug(username)
        log.debug(password)
        my_sql = PyMysql()
        con = my_sql.get_connection()
        # 如果是BOSS系统则鉴权通过
        if (username, password) == ('admin', 'admin123'):
            return func(*args, **kwargs)
        with con.cursor() as cursor:
            sql = 'SELECT username,password,salt,active,ip FROM gards_fidis WHERE username= %s'
            cursor.execute(sql, (username,))
            result = cursor.fetchone()
            con.commit()
            if not result:
                return auth_fail("invalid username")
            ip_fidis = result['ip']
            active = result['active']
            if active != 1:
                return auth_fail('username not active')
            # IP 检测, IP 项为空不检测
            if ip_fidis is not None and ip_fidis != '':
                ip__fidis_array = ip_fidis.split('.')
                ip_remote_array = ip_remote.split('.')
                for i in range(len(ip__fidis_array)):
                    if ip__fidis_array[i] == '*':
                        continue
                    if ip_remote_array[i] != ip__fidis_array[i]:
                        return auth_fail("wrong ip")
            # 密码检测
            fidis_pass = result['password']
            salt = result['salt']
            input_sha1 = password + salt
            output_sha1 = hashlib.sha1(input_sha1.encode('utf-8')).hexdigest()
            if output_sha1 != fidis_pass:
                return auth_fail("wrong password")
        return func(*args, **kwargs)
    return wrapper